package com.lebang.component;

import com.alibaba.fastjson.JSON;
import com.lebang.common.Constant;
import com.lebang.entity.buss.RecordMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *  推送的服务线程
 */
@Slf4j
@Component
public class MemberMsgThreadComponent implements DisposableBean, Runnable {
    private volatile boolean someCondition;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private UMengPushComponent uMengPushComponent;

    MemberMsgThreadComponent() {
        someCondition = true;
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        try {
            Thread.sleep(60000);
            log.info("推送线程开始执行……");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (someCondition) {
            try {
                Thread.sleep(500);
                try {
                    String str = redisClient.rpop(Constant.NEW_RECORD_QUE);
                    if (str != null && !"".equals(str)) {
                        RecordMsg recordMsg = JSON.parseObject(str, RecordMsg.class);
                        uMengPushComponent.sendNoRead(recordMsg.getMemberId(), recordMsg.getTitle(), recordMsg.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void destroy() {
        someCondition = false;
    }
}
